<?php
/**
 * Created by PhpStorm.
 * User: zhongbaitong
 * Date: 2020/1/9
 * Time: 11:07
 */

namespace app\user\home;

use app\common\controller\ApiBase;
use app\Common\exception\ApiError;
use app\user\model\User;
use hisi\Http;

/**
 * 登录模块
 * Class Token
 * @package app\user\home
 */
class Token extends ApiBase
{
    /**
     * 微信小程序登录处理
     * @params code（必须）
     * @params is_authorize（必须） 是否授权
     * @params avatar 微信头像
     * @params nickname 微信昵称
     * @params 其它如: 性别(gender)、省份(province)、城市(city)等
     * @throws \app\common\exception\ApiError
     */
    public function get(){
        $input = $this->getInput("code,is_authorize");

        $resp = $this->getSession($input['code']);
        $params = array_merge($input,$resp);

        $is_new_user = User::where("openid",$params["openid"])->count();
        if(!$is_new_user){
            $user = User::firstLogin($params);
        }
        else{
            $user = User::againLogin($params);
        }

        // 生成Token
        $token = str_encrypt($user->id . '/' . time()
            , md5(config('wechat.token_yan')));
        $data = compact('token');

        return $this->apiReturn(compact("data"));
    }

    /**
     * 通过 code 换取 openid
     * @param $js_code
     * @return mixed
     * @throws \app\common\exception\ApiError
     */
    public function getSession($js_code)
    {
        $url        = config('wechat.login_url');
        $appid      = config('wechat.app_id');
        $secret     = config('wechat.app_secret');
        $grant_type = 'client_credential';

        $resp = Http::get($url, compact('appid', 'secret', 'js_code', 'grant_type'));
        $resp = json_decode($resp, 1);

        if (array_key_exists('errcode', $resp)){
            throw new ApiError('get openid error：'.$resp['errmsg'],$resp['errcode']);
        }

        return $resp;
    }

}